package com.xsq.audio.player.playlist

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import com.xsq.audio.AudioItemData
import com.xsq.audio.R
import com.xsq.audio.databinding.ItemAudioListBinding

/**
 *
 *
 * Created by Shiquan.Xiao on 2023/4/3.
 */
class PlayListAdapter(private var audioList: List<AudioItemData>): RecyclerView.Adapter<PlayListAdapter.PlayListViewHolder>() {

    private val oldSelectPos = MutableLiveData(-1)
    private var onClick: ((Int, Int)->Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlayListViewHolder {
        val binding =
            ItemAudioListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return PlayListViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return audioList.size
    }

    override fun onBindViewHolder(holder: PlayListViewHolder, position: Int) {
        val data = audioList[position]

        holder.binding.tvTitle.text = data.name
        val context = holder.binding.root.context

        if (data.isSelect) {
            holder.binding.tvTitle.setTextColor(ContextCompat.getColor(context, R.color.setting_blue))
        } else {
            holder.binding.tvTitle.setTextColor(ContextCompat.getColor(context, R.color.textColorPrimary))
        }

        holder.binding.root.setOnClickListener {
            onClick?.let { it1 -> it1(position, oldSelectPos.value!!) }

            oldSelectPos.postValue(position)
        }
    }

    fun setOnItemClickListener(listener: (Int, Int) -> Unit) {
        this.onClick = listener
    }

    fun setNewAudioList(audioList: MutableList<AudioItemData>) {
        this.audioList = audioList
    }

    fun oldSelectPos(): LiveData<Int?> {
        return oldSelectPos
    }

    fun setOldSelectPos(pos: Int) {
        oldSelectPos.value = pos
    }

    inner class PlayListViewHolder(var binding: ItemAudioListBinding): RecyclerView.ViewHolder(binding.root)

}